﻿using System;
using System.IO;
using System.Text;
using System.Web;
using System.Net;

namespace CakemailIntegration
{
    /// <summary>
    /// Summary description for RegisterSubscriber
    /// </summary>
    public class RegisterSubscriber : IHttpHandler
    {
        private string _userKey = string.Empty; //take from config
        private string _apiKey = string.Empty; //take from config
        private string _clientId = string.Empty; //take from config
        private string _listMasterEnglish = string.Empty; //take from config
        private string _listMasterFrench = string.Empty; //take from config
        private string _listIdEnglish = string.Empty; //take from config
        private string _listIdFrench = string.Empty; //take from config

        public void ProcessRequest(HttpContext context)
        {
            var req = WebRequest.Create("https://api.wbsrvc.com/List/subscribeEmail/");
            req.Method = "POST";
            var encoding = new ASCIIEncoding();

            var form = context.Request.Form;

            if (form.Count < 1)
            {
                return;
            }

            var masterList = _listMasterEnglish;
            var referralList = _listIdEnglish;
            var redirectURL = string.Empty; // take from config ex. "http://site/index.php/home/newsletter_confirm_en/";

            if (context.Request.QueryString["l"] == "fr")
            {
                masterList = _listMasterFrench;
                referralList = _listIdFrench;
                redirectURL = string.Empty; // take from config ex. "http://site/fr/index.php/home/newsletter_confirm_fr/";
            }

            //send initial subscription
            var data = CreateMainRequest(masterList, form["email"], form["full_name"], form["postal_code"],
                                         form["telephone"]);
            byte[] byte1 = encoding.GetBytes(data);

            req.ContentType = "application/x-www-form-urlencoded";
            req.ContentLength = byte1.Length;
            req.Headers.Add("apikey", _apiKey);
            var newStream = req.GetRequestStream();
            newStream.Write(byte1, 0, byte1.Length);
            newStream.Close();

            //Send Referrals
            var numberOfreferrals = (form.Count - 4)/2;

            for (int i = 1; i <= numberOfreferrals; i++ )
            {
                Stream innerStream = null;
                try
                {
                    var innerReq = WebRequest.Create("https://api.wbsrvc.com/List/subscribeEmail/");
                    innerReq.Method = "POST";
                    if (!string.IsNullOrWhiteSpace(form["friend_email" + i]))
                    {
                        data = CreateReferralRequest(referralList, form["friend_email" + i],
                                                     form["friend_name" + i], form["email"], form["full_name"]);

                       innerReq.ContentType = "application/x-www-form-urlencoded";
                        byte1 =
                            encoding.GetBytes(data);
                        innerReq.ContentLength = byte1.Length;
                        innerReq.Headers.Add("apikey", _apiKey);
                        innerStream = innerReq.GetRequestStream();
                        innerStream.Write(byte1, 0, byte1.Length);
                    }
                }
                catch
                {
                }
                finally
                {
                    if (innerStream != null)
                    {
                        innerStream.Close();
                    }
                }
            }

            context.Response.Redirect(redirectURL);
        }

        private string CreateMainRequest(string list,string email,string name,string postalcode,string telephone)
        {
            return string.Format("user_key={0}&list_id={1}&client_id={2}&email={3}&no_triggers=true&data[full_name]={4}&data[postal_code]={5}&data[telephone]={6}",_userKey,list,_clientId,email,name,postalcode,telephone);
        }

        private string CreateReferralRequest(string list, string email, string name, string referEmail,string referrerName)
        {
            return string.Format("user_key={0}&list_id={1}&client_id={2}&email={3}&no_triggers=false&data[full_name]={4}&data[referred_by]={5}&data[referrer_name]={6}", _userKey, list, _clientId, email, name,referEmail,referrerName);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}